package com.itita.ww2.handler.requesthandler.shop;

import java.sql.SQLException;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.data.shop.ShopConfig;
import com.itita.ww2.enums.WW2ExceptionCode;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.enums.ResourceType;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.handler.IRequestOper;

/**
 * 购买资源
 * 花费金条 R004
 * @author NorthLan
 *
 */
public class BuyResource implements IRequestOper {

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		String key = params.getUtfString("key");

		ISFSObject goods = ShopConfig.getResourceShopItems();
		if (!goods.containsKey(key)) {
			throw new WW2Exception(WW2ExceptionCode.NOT_FOUND);
		}

		ISFSObject item = goods.getSFSObject(key);
		// 价格
		int price = item.getInt("price");
		if (!userProfile.getResManager().isResEnoughSingle(ResourceType.GOLD, price)) {
			throw new WW2Exception(WW2ExceptionCode.USER_RES_NOT_ENOUGH);
		}
		String resCode = item.getUtfString("code");
		int amount = item.getInt("amount");
		// 加资源啦
		userProfile.getResManager().operRes(resCode, amount);
		// 扣除金条
		userProfile.getResManager().operRes(ResourceType.GOLD, -price);
		// 
		userProfile.getResManager().update();
		userProfile.getResManager().sync();

		ISFSObject resObj = SFSObject.newInstance();
		resObj.putInt(resCode, amount);
		ISFSObject backObj = SFSObject.newInstance();
		backObj.putSFSObject("res", resObj);
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return false;
	}

}
